package com.hnd.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import com.hnd.springframework.beans.BeansException;
import com.hnd.springframework.beans.PropertyValue;
import com.hnd.springframework.beans.PropertyValues;
import com.hnd.springframework.beans.factory.config.BeanDefinition;
import com.hnd.springframework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;

/**
 * 负责bean的实例化，以及依赖的注入
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {
    InstantiationStrategy simpleInstantiationStrategy = new SimpleInstantiationStrategy();

    /**
     * 创建bean实例 注入属性
     *
     * @param beanName
     * @param beanDefinition
     * @param args
     * @return
     */
    @Override
    public Object createBean(String beanName, BeanDefinition beanDefinition, Object... args) {
        Object beanInstance = createBeanInstance(beanName, beanDefinition, args);
        applyProperValues(beanName, beanInstance, beanDefinition);
        return beanInstance;
    }

    /**
     * 创建bean实例
     *
     * @param beanName
     * @param beanDefinition
     * @param args
     * @return
     */
    public Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object... args) {
        Class beanClass = beanDefinition.getBeanClass();
        if (args == null) {
            return simpleInstantiationStrategy.instantiate(beanName, beanDefinition, null, args);
        }

        Constructor constructorToUser = null;
        Constructor[] constructors = beanClass.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            if (constructor.getParameterTypes().length == args.length) {
                constructorToUser = constructor;
            }
        }
        return simpleInstantiationStrategy.instantiate(beanName, beanDefinition, constructorToUser, args);

    }

    protected void applyProperValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        PropertyValue[] propertyValues = beanDefinition.getPropertyValues().getPropertyValues();
        try {
            for (PropertyValue pv : propertyValues) {
                String name = pv.getName();
                Object value = pv.getValue();
                if (value instanceof BeanReference) {
                    value = getBean(((BeanReference) value).getBeanName());
                }
                BeanUtil.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            throw new BeansException("Error setting property values：" + beanName);
        }

    }


}
